package com.moyun.common.aspect;

import cn.smallbun.screw.core.util.StringUtils;
import com.moyun.common.annotation.DataPermission;
import com.moyun.common.enums.DataScopeEnum;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author yangboxuan
 * @Description 数据过滤处理
 * @Date 2022/10/20 14:17
 */
@Aspect
@Component
public class DataAuthScopeAspect {
    public static final ThreadLocal<String> DATA_AUTH_THREAD_LOCAL = new ThreadLocal<>();

    @Before("@annotation(controllerDataAuthScope)")
    public void doBefore(JoinPoint point, DataPermission controllerDataAuthScope) throws Throwable {
        DATA_AUTH_THREAD_LOCAL.remove();
        handleDataAuthScope(point, controllerDataAuthScope);
    }

    @After("@annotation(controllerDataAuthScope)")
    public void doAfter(DataPermission controllerDataAuthScope) throws Throwable {
        /**
        * 清空数据权限拼接SQL
        */
        DATA_AUTH_THREAD_LOCAL.remove();
    }

    /**
     * 处理数据权限
     *
     * @param joinPoint     切面
     * @param dataAuthScope 数据权限
     */
    protected void handleDataAuthScope(final JoinPoint joinPoint, DataPermission dataAuthScope) {
        /**
         * 获取当前用户
         */
//        if (null == currentUser) {
//            return;
//        }

        List<Object> departModelList = new ArrayList<>();
        List<String> departIdList = new ArrayList<>();
        List<String> userNameList = new ArrayList<>();

        for (Object departModel : departModelList) {
            if (DataScopeEnum.DATA_SCOPE_ALL.getCode().equals(1)) {
                continue;
            } else if (DataScopeEnum.DATA_SCOPE_DEPT.getCode().equals(2)) {
                departIdList.add("departId");
            } else if (DataScopeEnum.DATA_SCOPE_DEPT_AND_CHILD.getCode().equals(3)) {
//                List<String> departIds = getChildDepartIdList(departModel);
//                if (!CollectionUtils.isEmpty(departIds)) {
//                    departIdList.addAll(departIds);
//                }
            } else if (DataScopeEnum.DATA_SCOPE_SELF.getCode().equals(4)) {
                userNameList.add("userName");
            }
        }

        StringBuilder sqlString = new StringBuilder();
        /**
         * 如果需要部门权限
         */
        if (!CollectionUtils.isEmpty(departIdList)) {
            sqlString.append(StringUtils.format(" OR {}dept_id IN ({})", dataAuthScope.deptAlias(), getDepartSqlStr(departIdList)));
        } else if (!CollectionUtils.isEmpty(userNameList)) {
            sqlString.append(StringUtils.format(" OR {}createBy = {}", dataAuthScope.userAlias(), "userName"));
        }

        if (StringUtils.isNotBlank(sqlString.toString())) {
            /**
             * 设置数据权限拼接sql
             */
            DATA_AUTH_THREAD_LOCAL.set(" AND (" + sqlString.substring(4) + ")");
        }
    }

//    /**
//     * 获取本部门和子部门ID列表
//     *
//     * @param departModel 部门信息
//     * @return 本部门和子部门ID列表
//     */
//    private static List<String> getChildDepartIdList(SysDepartModel departModel) {
//        String id = departModel.getId();
//        String fullPath = departModel.getFullPath();
//        String childIds = fullPath.substring(fullPath.indexOf(id), fullPath.length());
//        String[] childArr = childIds.split(",");
//        return Arrays.asList(childArr);
//    }

    /**
     * 拼接部门sql
     *
     * @param departIdList 部门ID列表
     * @return 拼接部门sql
     */
    private static String getDepartSqlStr(List<String> departIdList) {
        if (CollectionUtils.isEmpty(departIdList)) {
            return null;
        }

        StringBuilder sql = new StringBuilder("'");
        departIdList.forEach(data -> {
            sql.append(data).append("'").append(",");
        });

        sql.delete(sql.length() - 1, sql.length());
        return sql.toString();
    }
}